package com.hxx.widget.richtext.views

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.hxx.widget.R
import com.hxx.widget.richtext.*

abstract class AbstractRichAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    var data = arrayListOf<RichEditorItem>().apply {
        add(RichTextItem())
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            typeAudio, typeText, typeCheckBox, typeImage -> {
                SimpleViewHolder(
                    LayoutInflater.from(parent.context).inflate(viewType, parent, false)
                )
            }
            else -> throw Exception("无法解析的视图类型")
        }
    }

    override fun onBindViewHolder(
        holder: RecyclerView.ViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        super.onBindViewHolder(holder, position, payloads)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (data[position]) {
            is RichTextItem -> onTextBind(data[position] as RichTextItem, holder.itemView,position)
            is RichImageItem -> onImageBind(data[position] as RichImageItem, holder.itemView,position)
            is RichTodoItem -> onCheckBoxBind(data[position] as RichTodoItem, holder.itemView,position)
            is RichAudioItem -> onAudioBind(data[position] as RichAudioItem, holder.itemView,position)
            else -> throw Exception("非正常数据类型")
        }
    }

    abstract fun onTextBind(item: RichTextItem, view: View, position: Int)
    abstract fun onImageBind(item: RichImageItem, view: View, position: Int)
    abstract fun onCheckBoxBind(item: RichTodoItem, view: View, position: Int)
    abstract fun onAudioBind(item: RichAudioItem, view: View, position: Int)

    override fun getItemViewType(position: Int): Int {
        return when (data[position]) {
            is RichTextItem -> typeText
            is RichImageItem -> typeImage
            is RichTodoItem -> typeCheckBox
            is RichAudioItem -> typeAudio
            else -> throw Exception("非正常数据类型")
        }
    }


    override fun getItemCount(): Int = data.size

    inner class SimpleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    companion object {
        /**
         * 纯文本类型
         */
        private val typeText = R.layout.widget_layout_rich_list_item_text

        /**
         * 选项框类型
         */
        private val typeCheckBox = R.layout.widget_layout_rich_list_item_checkbox

        /**
         * 纯图片类型
         */
        private val typeImage = R.layout.widget_layout_rich_list_item_image

        /**
         * 纯语音类型
         */
        private val typeAudio = R.layout.widget_layout_rich_list_item_audio
    }
}